import { POWERUP_TYPES, POWERUP_DURATION, POWERUP_CONFIG } from './config.js';

export class PowerupSystem {
    constructor(scene) {
        this.scene = scene;
        this.powerups = [];
        this.powerupEffects = Object.fromEntries(
            Object.values(POWERUP_TYPES).map(type => [type, false])
        );
        this.powerupTimers = Object.fromEntries(
            Object.values(POWERUP_TYPES).map(type => [type, 0])
        );
        this.originalSpeed = null; // 记录原始速度
        
        // 加载SVG纹理
        this.textures = {};
        const textureLoader = new THREE.TextureLoader();
        
        // 为每种道具类型加载对应的SVG纹理
        const svgPaths = {
            [POWERUP_TYPES.SPEED]: 'assets/images/powerup_speed.svg',
            [POWERUP_TYPES.SHIELD]: 'assets/images/powerup_shield.svg',
            [POWERUP_TYPES.MAGNET]: 'assets/images/powerup_magnet.svg',
            [POWERUP_TYPES.SLOW]: 'assets/images/powerup_invincible.svg'  // 用无敌星星图标代替减速
        };

        Object.entries(svgPaths).forEach(([type, path]) => {
            textureLoader.load(path, (texture) => {
                texture.colorSpace = THREE.SRGBColorSpace;
                this.textures[type] = texture;
                // 更新对应材质的贴图
                if (this.materials[type]) {
                    this.materials[type].map = texture;
                    this.materials[type].needsUpdate = true;
                }
            });
        });

        // 创建精灵材质
        this.materials = Object.fromEntries(
            Object.entries(POWERUP_CONFIG.COLORS).map(([type, color]) => [
                type,
                new THREE.SpriteMaterial({
                    transparent: true,
                    opacity: 1
                })
            ])
        );
    }

    createPowerup(type, position) {
        // 使用精灵代替网格
        const sprite = new THREE.Sprite(this.materials[type]);
        
        // 如果纹理已加载，则使用它
        if (this.textures[type]) {
            sprite.material.map = this.textures[type];
        }
        
        // 设置精灵大小
        sprite.scale.set(3, 3, 1);
        sprite.position.copy(position);
        sprite.type = type;
        sprite.collected = false;
        
        this.powerups.push(sprite);
        this.scene.add(sprite);
        return sprite;
    }

    applyPowerup(type, panSpeed, player) {
        this.powerupEffects[type] = true;
        this.powerupTimers[type] = POWERUP_DURATION[type];
        
        switch(type) {
            case POWERUP_TYPES.SPEED:
                // 记录原始速度
                if (this.originalSpeed === null) {
                    this.originalSpeed = panSpeed;
                }
                panSpeed = panSpeed * 1.5; // 在当前速度基础上增加50%
                break;
            case POWERUP_TYPES.SHIELD:
                player.hit = false;
                break;
            case POWERUP_TYPES.SLOW:
                // 记录原始速度
                if (this.originalSpeed === null) {
                    this.originalSpeed = panSpeed;
                }
                panSpeed = player.baseSpeed * 0.5;
                break;
        }

        this.updatePowerupUI(type);
        return panSpeed;
    }

    updatePowerupUI(type) {
        // 创建或获取道具效果容器
        let powerupContainer = document.querySelector('.powerup-container');
        if (!powerupContainer) {
            powerupContainer = document.createElement('div');
            powerupContainer.className = 'powerup-container';
            powerupContainer.style.position = 'fixed';
            powerupContainer.style.top = '50px';
            powerupContainer.style.right = '20px';
            powerupContainer.style.display = 'flex';
            powerupContainer.style.flexDirection = 'column';
            powerupContainer.style.gap = '10px';
            document.body.appendChild(powerupContainer);
        }

        // 移除已存在的相同类型道具UI
        const existingPowerup = document.querySelector(`.powerup-indicator.${type}`);
        if (existingPowerup) {
            existingPowerup.remove();
        }

        const powerupElement = document.createElement('div');
        powerupElement.className = `powerup-indicator ${type}`;
        powerupElement.style.padding = '15px';
        powerupElement.style.backgroundColor = `rgba(${type === POWERUP_TYPES.SPEED ? '0,255,0' : type === POWERUP_TYPES.SHIELD ? '0,0,255' : type === POWERUP_TYPES.MAGNET ? '255,0,255' : '255,255,0'},0.8)`;
        powerupElement.style.borderRadius = '10px';
        powerupElement.style.minWidth = '150px';
        powerupElement.style.textAlign = 'center';
        powerupElement.style.fontFamily = 'Arial, sans-serif';
        powerupElement.style.fontSize = '16px';
        powerupElement.style.fontWeight = 'bold';
        powerupElement.style.color = '#ffffff';
        powerupElement.style.textShadow = '2px 2px 4px rgba(0,0,0,0.7)';
        powerupElement.style.display = 'flex';
        powerupElement.style.flexDirection = 'column';
        powerupElement.style.gap = '8px';
        powerupElement.style.boxShadow = '0 4px 8px rgba(0,0,0,0.3)';
        powerupElement.style.border = '2px solid white';
        powerupElement.style.animation = 'powerupPulse 2s infinite';
        
        const nameElement = document.createElement('div');
        nameElement.textContent = type === POWERUP_TYPES.SPEED ? '加速' :
                                type === POWERUP_TYPES.SHIELD ? '护盾' :
                                type === POWERUP_TYPES.MAGNET ? '磁铁' :
                                '减速';
        powerupElement.appendChild(nameElement);
        
        const timerElement = document.createElement('div');
        timerElement.className = 'powerup-timer';
        timerElement.style.fontSize = '14px';
        powerupElement.appendChild(timerElement);
        
        // 将道具效果添加到容器中
        powerupContainer.appendChild(powerupElement);

        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes powerupPulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }
        `;
        document.head.appendChild(style);
    }

    update(player, panSpeed) {
        // 更新道具位置和检测碰撞
        for (let i = this.powerups.length - 1; i >= 0; i--) {
            const powerup = this.powerups[i];
            if (!powerup.collected) {
                powerup.position.z += panSpeed;
                
                // 检测道具碰撞
                let dist = player.pos.distanceTo(powerup.position);
                
                // 磁铁效果时增加收集范围
                let collectRange = this.powerupEffects[POWERUP_TYPES.MAGNET] ? player.magnetRange : 2;
                
                if (dist < collectRange) {
                    powerup.collected = true;
                    this.scene.remove(powerup);
                    panSpeed = this.applyPowerup(powerup.type, panSpeed, player);
                    this.powerups.splice(i, 1);
                }
                
                // 移除超出范围的道具
                if (powerup.position.z > player.pos.z + 20) {
                    this.scene.remove(powerup);
                    this.powerups.splice(i, 1);
                }
            }
        }

        // 更新道具时间
        Object.keys(this.powerupTimers).forEach(type => {
            if (this.powerupEffects[type]) {
                this.powerupTimers[type] -= 16.67; // 约60帧每秒
                
                // 更新倒计时显示
                const timerElement = document.querySelector(`.powerup-indicator.${type} .powerup-timer`);
                if (timerElement) {
                    const secondsLeft = Math.max(0, Math.ceil(this.powerupTimers[type] / 1000));
                    timerElement.textContent = `剩余时间：${secondsLeft}秒`;
                }
                
                // 检查是否结束
                if (this.powerupTimers[type] <= 0) {
                    this.powerupEffects[type] = false;
                    this.powerupTimers[type] = 0;
                    
                    // 重置效果
                    if (type === POWERUP_TYPES.SPEED || type === POWERUP_TYPES.SLOW) {
                        // 恢复原始速度
                        if (this.originalSpeed !== null) {
                            panSpeed = this.originalSpeed;
                            this.originalSpeed = null;
                        } else {
                            panSpeed = player.baseSpeed;
                        }
                    }
                    
                    // 移除UI显示
                    const powerupElement = document.querySelector(`.powerup-indicator.${type}`);
                    if (powerupElement) {
                        powerupElement.remove();
                    }
                }
            }
        });

        // 随机生成道具
        if (Math.random() < POWERUP_CONFIG.SPAWN_CHANCE && this.powerups.length < POWERUP_CONFIG.MAX_COUNT) {
            const types = Object.values(POWERUP_TYPES);
            const randomType = types[Math.floor(Math.random() * types.length)];
            
            // 使用与障碍物相同的X轴位置逻辑
            let randomX = POWERUP_CONFIG.POSITIONS.CENTER;
            const dirR = Math.random();
            if (dirR <= 0.33) randomX = POWERUP_CONFIG.POSITIONS.LEFT;
            if (dirR >= 0.66) randomX = POWERUP_CONFIG.POSITIONS.RIGHT;
            
            const randomY = Math.random() * 11 + 2;
            this.createPowerup(
                randomType,
                new THREE.Vector3(randomX, randomY, player.pos.z - POWERUP_CONFIG.SPAWN_DISTANCE)
            );
        }

        return panSpeed;
    }

    reset() {
        // 清除所有道具
        for (let i = this.powerups.length - 1; i >= 0; i--) {
            this.scene.remove(this.powerups[i]);
        }
        this.powerups.length = 0;

        // 清除所有效果
        Object.keys(this.powerupEffects).forEach(type => {
            this.powerupEffects[type] = false;
            this.powerupTimers[type] = 0;
        });

        // 重置原始速度
        this.originalSpeed = null;

        // 清除UI显示
        const powerupContainer = document.querySelector('.powerup-container');
        if (powerupContainer) {
            powerupContainer.remove();
        }
    }
} 